const express = require('express');
const soketio = require('socket.io');
const http = require('http');
const cros = require('cors');
// 获取操作user的函数
const { addUser, removeUser, getUser, getUserInRoom } = require('./users');

// 路由
const router = require('./router');

// 可以从命令行传入端口，或者默认为5000
const PORT = process.env.PORT || 5000;



/* app->http->socket(express->http-> socket) */
const app = express();
// 使用路由
app.use(router);
// 允许跨域
app.use(cros());
const server = http.createServer(app);
const io = soketio(server);



/*  */
io.on('connection', (socket) => {
    console.log('there is a socket connection');

    /* 添加用户 */
    socket.on('join', ({ name, room }, callback) => {
        const { error, user } = addUser({ id: socket.id, name, room });
        if (error) return callback(error);
        socket.join(user.room);
        socket.emit('message', { user: 'admin', text: `${user.name},欢迎来到房间${user.room}` });
        socket.broadcast.to(user.room).emit('message', { user: 'admin', text: `${user.name},加入了聊天` });
        io.to(user.room).emit('roomData', { room: user.room, users: getUserInRoom(user.room) });

        callback({});
    })

    socket.on('sendMessage', (message, callback) => {
        const user = getUser(socket.id);
        console.log(user);
        io.to(user.room).emit('message', { user: user.name, text: message });
        io.to(user.room).emit('roomData', { room: user.room, users: getUserInRoom(user.room) });

        callback();

    })

    /* 在刷新页面是，会关闭socket,重建立一个socket */
    socket.on('disconnect', () => {
        const user = removeUser(socket.id);
        if (user) {
            io.to(user.room).emit('message', { user: 'admin', text: `${user.name} has left` });
        }
    });

    return () => {
        // 关闭链接
        socket.emit('disconnect');
        socket.off();
    }
})

server.listen(PORT, () => {
    console.log(`后台启动在端口${PORT}`);
})